<template>
  <a-row :gutter="16">
    <a-col :span="12">
      <a-card style="height: 750px;overflow-y: auto">
        <a-button type="primary" style="margin-bottom: 20px;" @click="handleAdd()">添加</a-button>
        <a-tree
            v-if="list.length"
            v-model:selectedKeys="selectedKeys"
            :tree-data="list"
            default-expand-all
            :field-names="{ children: 'children', title:'orgName', key:'id' }"
            @select="handleSelect"
        >
          <template #title="item">
            <a-dropdown :trigger="['contextmenu']">
              <div>
                <span>{{ item.orgName }}</span>
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item v-if="item.indexLevel < 2" key="add" @click="handleAddUnder(item)">添加下一级
                  </a-menu-item>
                  <!--                  <a-menu-item key="edit" @click="handleEdit(item)">编辑</a-menu-item>-->
                  <a-popconfirm v-if="item.indexLevel > 1" :title="`确定删除${item.orgName}？`"
                                @confirm="handleRemove(item)">
                    <a-menu-item key="del">删除</a-menu-item>
                  </a-popconfirm>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </a-card>
    </a-col>
    <a-col :span="12">
      <org-form ref="orgFormRef" @ok="handleOk"/>
    </a-col>
  </a-row>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { SysOrg } from '@/config/common'
import OrgForm from './modules/OrgForm.vue'
import { getOrgs, removeOrg } from '@/api/sys-org'

const orgFormRef = ref<InstanceType<typeof OrgForm>>()

const list = ref<SysOrg[]>([])

const selectedKeys = ref<string[]>([])

// const handleAdd = () => {
//   orgFormRef.value.open('新增机构', {
//     indexLevel: 1
//   })
//   selectedKeys.value = []
// }

const handleAddUnder = (item: SysOrg) => {
  orgFormRef.value.open('新增机构', {
    parentId: item.id,
    parentName: item.orgName,
    indexLevel: item.indexLevel + 1
  })
  selectedKeys.value = []
}

const handleEdit = (item: SysOrg) => {
  orgFormRef.value.open('编辑机构', item)
  selectedKeys.value = [item.id]
}

const handleSelect = (keys: string[], e) => {
  selectedKeys.value = [e.id]
  handleEdit(e.node.dataRef)
}

const handleOk = () => {
  loadData()
  selectedKeys.value = []
}

const handleRemove = async (item: SysOrg) => {
  await removeOrg(item.id)
  message.success('操作成功')
  await loadData()
  if (selectedKeys.value[0] === item.id) {
    selectedKeys.value = []
  }
}

const loadData = async () => {
  list.value = await getOrgs()
}

loadData()

</script>
<style>

</style>
